package com.ld.shieldsb.common.core.util;

import java.util.ArrayList;
import java.util.List;

//获取调用类
public class StackTraceUtil {

    // 返回字符串
    public static String getTrace() {
        StackTraceElement stack[] = Thread.currentThread().getStackTrace();
        String msg = "called by {";
        for (StackTraceElement ste : stack) {
            String callName = ste.getClassName();
            if (callName.startsWith("com.") && !callName.equals(StackTraceUtil.class.getName())) {
//                String calssName = ste.getClassName().substring(ste.getClassName().lastIndexOf(".") + 1, ste.getClassName().length());
//                msg += " at " + ste.getClassName() + "." + ste.getMethodName() + "(" + calssName + ".java:" + ste.getLineNumber() + ")\n";
                msg += "\n " + ste;
            }
        }
        msg += "\n}";
        return msg;
    }

    // 返回集合
    public static List<StackTraceElement> getTraceEleList() {
        List<StackTraceElement> eleList = new ArrayList<StackTraceElement>();
        StackTraceElement stack[] = Thread.currentThread().getStackTrace();
        for (StackTraceElement ste : stack) {
            String callName = ste.getClassName();
            if (callName.startsWith("com.") && !callName.equals(StackTraceUtil.class.getName())) {
                eleList.add(ste);
            }
        }
        return eleList;
    }

    /**
     * 获取最后一个调用的堆栈信息
     * 
     * @Title getLastTraceEle
     * @author 吕凯
     * @date 2019年3月30日 上午10:17:19
     * @return StackTraceElement
     */
    public static StackTraceElement getLastTraceEle() {
        List<StackTraceElement> eleList = getTraceEleList();
        if (eleList != null && eleList.size() > 0) {
            return eleList.get(0);
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(getTrace() + "==\n" + StackTraceUtil.class.getName());
    }

}
